import { Component, EventEmitter, OnInit, Output } from "@angular/core";
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { NzMessageService } from "ng-zorro-antd/message";
import { SystemConfigService } from "../../system-config/system-config.service";
import { NzTreeNode } from "ng-zorro-antd/tree";
import { GenerateCodeConfigService } from "../generate-code-config.service";

@Component({
  selector: "app-generate-code-edit",
  templateUrl: "./generate-code-edit.component.html",
  styles: []
})
export class GenerateCodeEditComponent implements OnInit {


  constructor(private formBuilder: FormBuilder,
              private msgSrv: NzMessageService,
              private generateCodeConfigService: GenerateCodeConfigService
  ) {
  }

  nzLoading = false;

  @Output() voted = new EventEmitter();

  validateForm!: FormGroup;

  // 是否编辑
  isUpdate = false;

  visible = false;

  open(): void {
    this.visible = true;
    this.isUpdate = false;
  }

  edit(param) {
    this.visible = true;
    this.isUpdate = true;

    if (param) {
      this.validateForm.patchValue(param);
    } else {
      this.validateForm.reset();
    }
  }

  close(): void {
    this.visible = false;
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.validateForm.invalid) {
      return;
    }

    this.nzLoading = true;

    this.generateCodeConfigService.update(this.validateForm.value).subscribe((res) => {

      this.nzLoading = false;

      if (res.code === 1) {
        this.msgSrv.success("保存完成");
        this.close();
        this.voted.emit();
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  ngOnInit(): void {

    this.validateForm = this.formBuilder.group({
      id: [null],
      code: [null, [Validators.required]],
      name: [null, [Validators.required]],
      prefix: [null],
      year: [null],
      month: [null],
      day: [null],
      initNumber: [null, [Validators.required]],
      numberLength: [null, [Validators.required]],
      increment: [null, [Validators.required]],
      idx: [null, [Validators.required]]
    });

  }

  nzDisplayWith(node: NzTreeNode) {
    return node.title;
  }

  onChange($event: string): void {
    console.log($event);
  }
}
